﻿var hostPath = window.location.protocol + "//" + window.location.host ;
$(document).ready(function () {
    pageLoad();
    validate();
    panelload();
    modalInit();
    TelerikCustom();
});

function panelload(){
    $('.panel').each(function () {
        var isCollapsed = $(this).find('.accordion-body').hasClass('collapse');
        if (isCollapsed) {
            $(this).find('.panel-heading').addClass('collapsed');
        }
    })
}

function modalInit() {
    $("[data-toggle='modal']").click(function () {
        var modal = $(this).attr('data-target');
        var url = $(this).attr('data-url');
        var title = $(this).attr('data-title');
        var closefunc = $(this).attr('data-closefunc');
        $(modal).find('iframe').attr('src', url);
        $(modal).find('.modal-title').text(title);
        $(modal).find('.modal-header .close').attr('onclick', closefunc);
        if (url.length != 0) {
           // $(modal).attr('data-target', "#myModal");
            $(modal).modal('show');
        }

    });
}
function modalClose() {
    window.parent.$('#myModal').modal('hide');
}

function LoadTotalOrderRequest() {
    $('.orderRequestQuantity').each(function () {
        txtQuantity_Keypress(this);
    })
}

function txtQuantity_Keypress(obj) {
    var tr = $(obj).closest('tr');
    var quantity = $(obj).val().trim().replace(",",'');

    var purchaseprice = $(tr).find('.purchase-price-hide').text();
    var total = $(tr).find('.total');
    var totalhide = $(tr).find('.total-hide');
    var total1 = parseFloat(quantity) * parseFloat(purchaseprice);
    if (isNaN(total1)) {
        total1 = 0;
    }

    if (total1 < 0) {
        total1 = 0;
    }

    $(total).text(total1);
    $(totalhide).text(total1);


    $(total).prettynumber({
        delimiter: ','
    })

    var sum = 0;
    $('.total-hide').each(function () {
        var total2 = parseFloat($(this).text());
        if (isNaN(total2)) {
            total2 = 0;
        }
        if (total2 < 0) {
            total2 = 0;
        }
        sum += total2;
    })



    $('.sum-total').text(sum);
    $('.sum-total').prettynumber({
        delimiter: ','
    })
    $('.sum-total').text('Tổng tiền thanh toán: ' + $('.sum-total').text());
}

//quicp
function txtKeyupRequireValue(obj, des) {

    var val = $.trim( $(obj).val());
    if (val.length != 0) {
        $(des).removeAttr('disabled');
        $(des).find('input').removeAttr('disabled');
    }
    else {
        $(des).attr('disabled', 'disabled');
        $(des).find('input').attr('disabled', 'disabled');
        $(des).find('input').prop('checked', true);
    }
}
// end quicp

function TelerikCustom() {
    $('.RadInput, .RadComboBox').each(function () {
        $(this).css('width', '');
    });

    
}
function pageLoad() {
    var manager = Sys.WebForms.PageRequestManager.getInstance();
    manager.add_beginRequest(AjaxPanelOnBeginRequest);
    manager.add_endRequest(onEachRequest);
}
function validate() {
    

    $("#aspnetForm").validateWebForm();
}

function rcbHierarchyClientClicking(sender, args) {
    //var comboBoxName = sender._clientStateFieldID.split('_')[0];
    var comboBoxName = sender.get_id().replace("_i0_tvHierarchy", "");
    var comboBox = $find(comboBoxName);

    var node = args.get_node()
    comboBox.set_text(node.get_text());

    comboBox.trackChanges();
    comboBox.get_items().getItem(0).set_text(node.get_text());
    comboBox.commitChanges();

    comboBox.hideDropDown();

    // Call comboBox.attachDropDown if:
    // 1) The RadComboBox is inside an AJAX panel.
    // 2) The RadTreeView has a server-side event handler for the NodeClick event, i.e. it initiates a postback when clicking on a Node.
    // Otherwise the AJAX postback becomes a normal postback regardless of the outer AJAX panel.

    comboBox.attachDropDown();
}
function openNewTab(url) {
    window.open(url);
}
function confirmBox(msg) {
    var r = false;
    r = confirm(msg);
    PageMethod("WebService.asmx/ConfirmBox", ['r',r], function (data) {
        alert(data.d);
    }, function () { });
}

function checkSessionLoginTab(btn) {
    var r;
    PageMethod('Default.aspx/CheckSessionLogin', [], function (data) {
        r = data.d;
        if (r === true) {
            var btnId = $(btn).attr('name');
            //  __doPostBack(btnId, '')
        }
        else {
            $('#popup-login-label').text('');
            $('#popup-login').modal('show');
        }
    });
    return false;
}


function checkSessionLogin(btn) {
    var r;
    PageMethod('Default.aspx/CheckSessionLogin', [], function (data) {
        r = data.d;
        if (r === true) {
            var btnId = $(btn).attr('name');
           __doPostBack(btnId, '')
        }
        else {
            $('#popup-login-label').text('');
            $('#popup-login').modal('show');
        }
    });
    return false;
}
function loginSessionLogin() {
    var r;
    var name = $('#txtLoginSessionName').val();
    var pass = $('#txtLoginSessionPass').val();

    PageMethod('Default.aspx/PopupLogin', ['username', name, 'password', pass], function (data) {
        r = data.d;
        if (r === true) {
            $('#popup-login').modal('hide');
            $('#popup-login-label').text('');
        }
        else {
            $('#popup-login-label').text('Đăng nhập không thành công!');
        }
    });
    return false;
}


function PageMethod(fn, paramArray, successFn, errorFn) {
    var pagePath = hostPath;
    

    //Create list of parameters in the form:  
    //{"paramName1":"paramValue1","paramName2":"paramValue2"}  
    var paramList = '';
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    //Call the page method
    $.ajax({
        type: "POST",
        url: pagePath + "/" + fn,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "json",
        success: successFn,
        error: errorFn
    });
}


function cboOnClientSelectedIndexChangedShowValue(sender, args) {
    var item = args.get_item();
    item.set_text(item.get_value());
}

function rcbHierarchyClientClickingByValue(sender, args) {
    //var comboBoxName = sender._clientStateFieldID.split('_')[0];
    var comboBoxName = sender.get_id().replace("_i0_tvHierarchy", "");
    var comboBox = $find(comboBoxName);

    var node = args.get_node()
    if (node.get_value() != null) {
        comboBox.set_text(node.get_value());
        comboBox.trackChanges();
        comboBox.get_items().getItem(0).set_text(node.get_value());
       
    }
    else {
        comboBox.set_text(node.get_text());
        comboBox.trackChanges();
        comboBox.get_items().getItem(0).set_text(node.get_text());
    }

    comboBox.commitChanges();
    comboBox.hideDropDown();

    // Call comboBox.attachDropDown if:
    // 1) The RadComboBox is inside an AJAX panel.
    // 2) The RadTreeView has a server-side event handler for the NodeClick event, i.e. it initiates a postback when clicking on a Node.
    // Otherwise the AJAX postback becomes a normal postback regardless of the outer AJAX panel.

    comboBox.attachDropDown();

}

function rcbHierarchyClientClickingByValueAndText(sender, args) {
    //var comboBoxName = sender._clientStateFieldID.split('_')[0];
    var comboBoxName = sender.get_id().replace("_i0_tvHierarchy", "");
    var comboBox = $find(comboBoxName);

    var node = args.get_node()
    var Text = node.get_value() + ' - ' + node.get_text();
    comboBox.set_text(Text);

    comboBox.trackChanges();
    comboBox.get_items().getItem(0).set_text(Text);
    comboBox.commitChanges();

    comboBox.hideDropDown();

    // Call comboBox.attachDropDown if:
    // 1) The RadComboBox is inside an AJAX panel.
    // 2) The RadTreeView has a server-side event handler for the NodeClick event, i.e. it initiates a postback when clicking on a Node.
    // Otherwise the AJAX postback becomes a normal postback regardless of the outer AJAX panel.

    comboBox.attachDropDown();
}

function rcbClientBlurByValue(sender, args) {
    //rcbHierarchyClientClickingByValue(sender, args);
    alert('fdfsd');
}
var parenItemSelected = false;
function OnClientNodeClicked(sender, args) {
    var currNode = args.get_item();
    var childNodes = currNode.get_allNodes();
    var nodeCount = currNode.get_childItems().length;
    var parentItem = currNode.get_parentItem();
    if (parentItem) {
        parenItemSelected = true;
        parentItem.set_selected(true);
    }
    if (currNode.get_selected()) {
        CheckAllChildren(childNodes, nodeCount);
    }
    else {
        UnCheckAllChildren(currNode, childNodes, nodeCount);
    }
    parenItemSelected = false;
}

function UnCheckAllChildren(currNode, nodes, nodecount) {
    var i;
    for (i = 0; i < nodecount; i++) {
        nodes[i].set_selected(false);
    }
    currNode.set_selected(false);
}
function OnClientItemClick() {
    alert("fdsfds");
}
function CheckAllChildren(nodes, nodecount) {
    var i;
    if (!parenItemSelected) {
        for (i = 0; i < nodecount; i++) {
            nodes[i].set_selected(true);
        }
    }
}

var progressbarTimeout;
function loadMessage(msg, isSuccess) {
    //var cls = 'alert-success';
    //if (isSuccess == false) cls = 'alert-danger';
    var cls = 'msgSuccess';
    if (isSuccess == false) cls = 'msgFailed';
    AjaxPanelResponseMessage(msg, cls);
}
function AjaxPanelResponseMessage(msg, cls) {
    //clearTimeout(progressbarTimeout)
    $('.progressbar').show();
    alertShow(cls, msg);
    
}
function alertShow(cls, msg) {
    if (cls == 'msgSuccess') cls = 'alert-success'
    else cls = 'alert-danger';
    $('body').find('.message').remove();
    $('body').append('<div class="message alert ' + cls + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + msg + '</div>');

 
    //alert(msg);

    setTimeout(function () {
        $('.message').fadeOut();
    }, 10000);

}
function onEachRequest(sender, args) {
    validate();
    validateOther();
    panelload();
    modalInit();
}
function validateOther() {
    $('.comboRequired input[type=hidden]').addClass('comboRequiredInput');
    $.validator.addMethod("comboRequiredInput", function (value, element) {
        var el = $(element);
        var json = $.parseJSON(el.val());
        var value = json.value;
        return $.trim(value).length > 0
    }, "Bạn chưa chọn giá trị, hoặc giá trị nhập chưa đúng!");

    //maxlength
    $.validator.addMethod("maxlength40", function (value, element) {
        var el = $(element);
        var length = el.val();
        return $.trim(length).length < 40
    }, "Vui lòng nhập tối đa 40 ký tự");

    $.validator.addMethod("maxlength400", function (value, element) {
        var el = $(element);
        var length = el.val();
        return $.trim(length).length < 400
    }, "Vui lòng nhập tối đa 400 ký tự");

    $.validator.addMethod("onlynumber", function (value, element) {
        var reg = /^\d+$/;
        var el = $(element);
        var val = el.val();
        if (val.length > 0)
            return reg.test(val);
        return true;
    }, "Vui lòng nhập kiểu số");

    $.validator.addMethod("onlyemail", function (value, element) {
        var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        var el = $(element);
        var val = el.val();
        if (val.length > 0)
            return reg.test(val);
        return true;
    }, "Vui lòng nhập email chính xác");

    $.validator.addMethod("maxlength800", function (value, element) {
        var el = $(element);
        var length = el.val();
        return $.trim(length).length < 800
    }, "Vui lòng nhập tối đa 800 ký tự");

    $.validator.addMethod("nosymbol", function (value, element) {
        var reg = /^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$/;
        var el = $(element);
        var val = el.val();

        return reg.test(val);
    }, "Vui lòng không nhập ký tự đặc biệt");

}
function AjaxPanelOnBeginRequest(sender, args) {
    $('.msgFailed').remove();
    $('.msgSuccess').remove();

}
function load() {
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(AjaxPanelResponseEnd);
}
function checkAll(o) {
    if (o.checked) {
        $(o).find('.ckbItem').attr('checked', 'checked');
    }
    else {
        $(o).find('.ckbItem').removeAttr('checked')
    }
}

function checkAllFilter(o) {
    if (o.checked) {
        $('.ckbItem input[type=checkbox]').prop('checked', true);
    }
    else {
        $('.ckbItem input[type=checkbox]').prop('checked', false);
    }
}

/* Hàm nhập số phân tách*/
function FormatNumber(obj) {
    var strvalue;
    if (eval(obj))
        strvalue = eval(obj).value;
    else
        strvalue = obj;
    var num;
    num = strvalue.toString().replace(/\$|\,/g, '');

    if (isNaN(num))
        num = "";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    num = Math.floor(num / 100).toString();
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
            num.substring(num.length - (4 * i + 3));
    //return (((sign)?'':'-') + num);
    eval(obj).value = (((sign) ? '' : '-') + num);
}


function ValidateKeyNumber(i) {
    if (i.value.length > 0) {
        i.value = i.value.replace(/[^\d]+/g, '');
    }
}

String.prototype.insert = function (index, string) {
    if (index > 0)
        return this.substring(0, index) + string + this.substring(index, this.length);
    else
        return string + this;
};
function ValidateHour(textbox) {
    var str = $(textbox).val();

    if (str.length == 4) {
        if (str[2] != ':')
            str = str.insert(2, ':');
        $(textbox).val(str);
    }

    if (str.length > 4) {
        var reg = /^([0-1][0-9]|2[0-3]):([0-5][0-9])$/;
        var val = $(textbox).val();
        if (reg.test(val) == false) {
            $(textbox).val('');
        }
    }
}

Date.prototype.toHHMMSS = function () {
    sec_numb = parseInt(this);
    var hours = Math.floor(sec_numb / 3600);
    var minutes = Math.floor((sec_numb - (hours * 3600)) / 60);
    var seconds = sec_numb - (hours * 3600) - (minutes * 60);

    if (hours < 10) { hours = "0" + hours; }
    if (minutes < 10) { minutes = "0" + minutes; }
    if (seconds < 10) { seconds = "0" + seconds; }
    var time = hours + ':' + minutes + ':' + seconds;
    return time;
}